package com.zyd.task;


import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.zyd.dao.CarLockDao;
import com.zyd.dao.VehicleDao;
import com.zyd.io.model.VehicleEntity;
import com.zyd.io.model.VehicleEntityExample;
import com.zyd.mappers.VehicleEntityMapper;
import com.zyd.message.MessageSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.util.List;

@Component
public class LockTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(LockTask.class);

    @Autowired
    private VehicleDao vehicleDao;

    @Autowired
    private VehicleEntityMapper mapper;

    @Autowired
    private CarLockDao carLockDao;

    //    @Scheduled(fixedDelay = 1000 * 60 * 60 * 5)
    @Scheduled(fixedDelay = 1000 * 5 * 60)
    public void checkStationStatus() throws ParseException {
        LOGGER.info("监听数据");
        //先查出所有的已锁车辆的tagcode
        List<String> tagcodes = vehicleDao.findTagcodeByLock(1);
        for (String tagcode : tagcodes) {//循环每一个
            //查出最新接受该标签的的基站,
            String baseid = vehicleDao.findNewBaseidByTagcode(tagcode);
            //比较最新的基站是否在锁车表中存在
            String stations = carLockDao.findStationsByTagcode(tagcode);
            if (!StringUtils.isEmpty(baseid) && !StringUtils.isEmpty(stations)) {
                if (!stations.contains(baseid)) { //如果不存在
                    VehicleEntityExample example = new VehicleEntityExample();
                    example.createCriteria().andTagcodeEqualTo(tagcode);
                    VehicleEntity vehicleEntity = mapper.selectByExample(example).get(0);
                    System.out.println("发送短信,提示");

                    send(vehicleEntity.getMobile(), vehicleEntity.getVinno());
                }
            }
        }


        LOGGER.info("监听数据结束");
    }


    @Autowired
    private MessageSender messageSender;

    @Value("${warnTemplateCode}")
    private String templateCode;
    @Value("${warnSignName}")
    private String signName;

    /**
     * 手机号,车牌号
     *
     * @param mobile
     * @param vinno
     */
    public void send(String mobile, String vinno) {
        try {
            SendSmsResponse sendSmsResponse = messageSender.sendSms(mobile, signName, templateCode, "{\"cph\":\"" + vinno + "\"}");
            System.out.println(sendSmsResponse.getMessage());
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

}


